package net.dgg.dggcloud.service.iboss.service.sc;

import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.iboss.constant.OriginCodeSource;
import net.dgg.dggcloud.service.iboss.constant.ScOperationConstant;
import net.dgg.dggcloud.service.iboss.constant.ScStatusConstant;
import net.dgg.dggcloud.service.iboss.entity.ScProFlowOperating;
import net.dgg.dggcloud.service.iboss.entity.ScProOrder;
import net.dgg.dggcloud.service.iboss.utils.DataWrap;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 刘阳
 * @ClassName <ScAutoAllotService>
 * @despriction 自动分配Service
 * @create 2018/06/21 17:27
 **/
@Service
public class ScAutoAllotService extends BaseService {

    /**
     * 订单自动分配
     *
     * @param ids
     */
    public void update_autoAllot(String ids) {
        Assert.hasText(ids, "订单ID不能为空！");
        String[] idsArr = ids.split(",");
        List<Long> idList = new ArrayList<>(idsArr.length);
        for (String s : idsArr) {
            idList.add(Long.valueOf(s));
        }
        Assert.isTrue(idList.size() > 0, "订单ID不能为空！");
        List<ScProOrder> scProOrderList = this.repository.getSession().createCriteria(ScProOrder.class).add(Restrictions.in("id", idList)).list();
        Assert.isTrue(scProOrderList.size() > 0, "未查询到生产订单！");
        String BUS_YT_ZJYW = "BUS_YT_ZJYW"; // 资金业务
        for (ScProOrder scProOrder : scProOrderList) {
            Assert.isTrue(ScStatusConstant.WAIT_ALLOCATION.equals(scProOrder.getStatus()), String.format("编号为%s的生产子订单已不是待分配状态！", scProOrder.getOrderBusinessNo()));
            Assert.isTrue(!BUS_YT_ZJYW.equals(scProOrder.getBtCode()), String.format("编号为%s的生产子订单是资金业务，无法自动分配！", scProOrder.getOrderBusinessNo()));
        }

        for (ScProOrder scProOrder : scProOrderList) {
            scProOrder.setStatus(ScStatusConstant.WAIT_SYS_ALLOCATION); // 带系统分配
            scProOrder.setOriginCode(OriginCodeSource.SC_ORIGINCODE_SYS_ALLOT); // 订单来源
            DataWrap.updateWraps(scProOrder); //更新操作人信息

            // 创建操作记录
            ScProFlowOperating scProFlowOperating = new ScProFlowOperating();
            scProFlowOperating.setOperationType(ScOperationConstant.OPERATION_ORDER_START_ALLOCATION);
            scProFlowOperating.setOperation("发起自动分配");
            scProFlowOperating.setProProductId(scProOrder.getId());
            scProFlowOperating.setProProductNo(scProOrder.getOrderBusinessNo());
            DataWrap.saveWrap(scProFlowOperating);
            scProFlowOperating.setCreateTime(new Date());
            scProFlowOperating.setId(this.keyWorker.nextId());

            this.repository.saveOrUpdate(scProOrder);
            this.repository.save(scProFlowOperating);
        }

    }

}
